package jh.com.jhappbf.unload;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import android.widget.Button;

import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;

import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request;
import com.android.volley.Response;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


import androidx.annotation.Nullable;
import jh.com.jhappbf.ComfirmListAdapter;
import jh.com.jhappbf.Interface.GetItemClick;
import jh.com.jhappbf.R;
import jh.com.jhappbf.configs.Constant;
import jh.com.jhappbf.dispatchcar.ContractSelect;
import jh.com.jhappbf.dispatchcar.DispatchCarAdd;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.DanhaoModel;
import jh.com.jhappbf.model.PihaoModel;
import jh.com.jhappbf.platenumber.PlateNumberSelect;
import jh.com.jhappbf.security.DES;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.WebServiceConnection;

/**
 * 作者：Created by GP on 2020/8/3.
 */
public class ConfirmActivity extends AbActivity implements View.OnClickListener , GetItemClick {

    private ListView mListView;
    private Button mBtnOk;
    private Button mRefreshOk;
    private Context mAppContext;

    private AbLoadDialogFragment mDialogFragment;

    private ArrayList<String> mData;//TextView名称集合
    private ArrayList<String> mDataZiDuan;//TextView名称集合
    private ComfirmListAdapter mAdapter;
    private Button mSearchImg;
    private TextView infoCargoname;
    private String jsonStr="";//批号实体类转json字符串
    private String flag="";//是否定额
    private String mType="";//类型（采购销售预留单）
    private String isCommit="0";//装卸货已确认,未确认 标记


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_confirm);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(R.string.unload_confirm_title);
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.drawable.line);
        mAppContext = getApplicationContext();
        mData=new ArrayList<>();
        mDataZiDuan=new ArrayList<>();
        flag=getIntent().getStringExtra("flag");
        mType=getIntent().getStringExtra("mType");
        isCommit=getIntent().getStringExtra("isCommit");
        initData();
        initView();
        getData();
    }

    private void initData() {
        mData.add("过磅单号");
        mData.add("订单号");
        mData.add("单号");
        mData.add("车牌号");
        mData.add("物料名");
        mData.add("类型");
        mData.add("毛重");
        mData.add("皮重");
        mData.add("误差值");
        mData.add("扣杂");
        mData.add("地点");
        mData.add("确认人");
        mData.add("工厂代码");
    }

    // /获取数据
    private void getData() {
        String methodName = "getSaverDaile";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("id");
        String id=getIntent().getStringExtra("saverid");
        value.add(id);
        Response.Listener<String> listener = response -> {
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            JSONObject jsonObject = JsonHelper.getJsonObject(response);
            if (jsonObject != null) {
                mAdapter.getContents().put("过磅单号",jsonObject.optString("id"));
                mAdapter.getContents().put("订单号",jsonObject.optString("S4"));
                mAdapter.getContents().put("单号",jsonObject.optString("S8"));
                mAdapter.getContents().put("物料名",jsonObject.optString("Cargoname"));
                mAdapter.getContents().put("车牌号",jsonObject.optString("Platenumber"));
                mAdapter.getContents().put("类型",jsonObject.optString("Type"));
                mAdapter.getContents().put("毛重",jsonObject.optString("Gross"));
                mAdapter.getContents().put("皮重",jsonObject.optString("Tare"));
                mAdapter.getContents().put("误差值",jsonObject.optString("S19"));
                mAdapter.getContents().put("确认人",State.mName);
                mAdapter.getContents().put("工厂代码",jsonObject.optString("S69"));
                mAdapter.notifyDataSetChanged();
            }
        };

        Response.ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ConfirmActivity.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Request.Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }


    private void initView() {
        mSearchImg = (Button) findViewById(R.id.unload_search_img);
        mSearchImg.setOnClickListener(this);
        infoCargoname=(TextView)findViewById(R.id.info);
        mBtnOk = (Button) findViewById(R.id.confirm_btn_ok);
        mBtnOk.setOnClickListener(this);

        mRefreshOk= (Button) findViewById(R.id.confirm_btn_refresh);
        mRefreshOk.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.add_list_view);
        mAdapter = new ComfirmListAdapter(this,mData,mDataZiDuan,this);
        mListView.setAdapter(mAdapter);
        if (TextUtils.equals("1",isCommit)){
            mBtnOk.setText("撤销确认");
        }

    }
    private final int GETPLAN = 0X001;
    private final int GETPLATENUM = 0X002;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.unload_search_img:
                Intent intent=new Intent(this,ContractSelect.class).putExtra("flag",mAdapter.getContents().get("车牌号"));
                startActivityForResult(intent, GETPLAN);
                break;
            case R.id.confirm_btn_refresh:
                refresh();
                break;
            case R.id.confirm_btn_ok:
                if (TextUtils.equals("1",isCommit)){
                    AlertDialog dialog= new AlertDialog.Builder(this).setTitle("提示")
                            .setCancelable(false).setMessage("是否撤销装卸货确认?")
                            .setPositiveButton("确定", (arg0, arg1) -> commitcancel())
                            .setNegativeButton("取消", (arg0, arg1) -> {
                                return;
                            }).create();
                    dialog.show();
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(40);
                    dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(40);
                }else {
                    AlertDialog dialog= new AlertDialog.Builder(this).setTitle("提示")
                            .setCancelable(false).setMessage("车辆信息读取正确,是否确认装卸货？")
                            .setPositiveButton("确定", (arg0, arg1) -> commitUnloads())
                            .setNegativeButton("取消", (arg0, arg1) -> {
                                return;
                            }).create();
                    dialog.show();
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(40);
                    dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(40);
                }

                break;
        }
    }

    private void commitcancel(){
        String mSaverId=mAdapter.getContents().get("过磅单号");
        String user=mAdapter.getContents().get("确认人");
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("id");
        param.add("user");
        value.add(mSaverId);
        value.add(user);
        String methodName = "unLoadYunTuCancel";
        mBtnOk.setEnabled(false);
        Response.Listener<String> listener = response -> {
            mBtnOk.setEnabled(true);
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null) {
                JSONObject obj = data.get(0);
                String result = obj.optString("result");
                AbToastUtil.showToast(ConfirmActivity.this, result);
            }
        };

        Response.ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ConfirmActivity.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            AbToastUtil.showToast(ConfirmActivity.this, "联网失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Request.Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }
    private void commitUnloads() {
        AbLoadDialogFragment mDialogFragment = AbDialogUtil.showLoadDialog(ConfirmActivity.this,
                R.mipmap.ic_load, "正在提交,请稍等...");
        String mSaverId=mAdapter.getContents().get("过磅单号");
        String address=TextUtils.isEmpty(mAdapter.getContents().get("地点"))?"":mAdapter.getContents().get("地点");
        String user=mAdapter.getContents().get("确认人");
        String Deduction=mAdapter.getContents().get("扣杂");
        String dispatchId=mAdapter.getContents().get("订单号");
        String jiaohuoId=mAdapter.getContents().get("单号");
        if(TextUtils.isEmpty(jsonStr)&&!TextUtils.isEmpty(jiaohuoId)){
            AbToastUtil.showToast(this,"请选择订单号！");
            return;
        }
        String methodName = "unLoadYunTu";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("id");
        param.add("address");
        param.add("user");
        param.add("Deduction");
        param.add("dispatchId");
        param.add("contents");
        param.add("norm");
        value.add(mSaverId);
        value.add(address);
        value.add(user);

        if (TextUtils.isEmpty(Deduction)){
            value.add("0");
        }else {
            value.add(Deduction);
        }
        value.add(dispatchId);
//        jsonStr= DES.encrypt(jsonStr,Constant.DESKEY);
        value.add(jsonStr);
        value.add(flag);
//        new Thread(() -> {
//            String results=WebServiceConnection.GetResultByService(Constant.WEBSERVICE,null,methodName,param,value);
//            runOnUiThread(() -> {
//                AbToastUtil.showToast(ConfirmActivity.this, "数据提交成功");
//                if (mDialogFragment != null) {
//                    mDialogFragment.dismiss();
//                }
//                mBtnOk.setEnabled(true);
//                if (results==null||results.length()==0)
//                    AbToastUtil.showToast(ConfirmActivity.this,"联网失败");
//                else {
//                    List<JSONObject> data = JsonHelper.getJsonObjects(results);
//                    if (data != null) {
//                        JSONObject obj = data.get(0);
//                        String result = obj.optString("result");
//                        if (result.length() == 0) {
//                            result = "确认失败!";
//                        }
//                        if (result.contains("成功")) {
//                            refresh();
//                        }
//
//                    }
//                }
//
//            });
//
//        }).start();
        Response.Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(ConfirmActivity.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            List<JSONObject> data = JsonHelper.getJsonObjects(response);
            if (data != null) {
                JSONObject obj = data.get(0);
                String result = obj.optString("result");
                if (result.length() == 0) {
                    result = "确认失败!";
                }
                if (result.contains("成功")) {
                    refresh();
                }
                AbToastUtil.showToast(ConfirmActivity.this, result);
            }
        };

        Response.ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(ConfirmActivity.this);
            if (mDialogFragment != null) {
                mDialogFragment.dismiss();
            }
            AbToastUtil.showToast(ConfirmActivity.this, "联网失败!");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Request.Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    private void refresh() {
        mAdapter.getContents().clear();
        mAdapter.getContents().put("确认人", State.mName);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String value = data.getStringExtra("result");
        switch (requestCode){
            case GETPLAN:

                StringBuilder builder=new StringBuilder();
                ArrayList<DanhaoModel> nowdanhaoModels = (ArrayList<DanhaoModel>) data.getSerializableExtra("danhaoModels");
                ArrayList<DanhaoModel> deldanhanModels=new ArrayList<DanhaoModel>();
                for (DanhaoModel danhaoModel:nowdanhaoModels) {
                    if (danhaoModel.isIscheck()){
                        builder.append(danhaoModel.getID()+",");
                    }else {
                        deldanhanModels.add(danhaoModel);
                    }
                }
                nowdanhaoModels.removeAll(deldanhanModels);
                if(builder.toString().length()>2){
                    mAdapter.getContents().put("订单号",builder.toString().substring(0,builder.toString().length()-1));
                    mAdapter.notifyDataSetChanged();
                    //提取所有已确认
                    ArrayList<PihaoModel>pihaoModels=new ArrayList<>();
                    for (DanhaoModel danhaoModel:nowdanhaoModels){
                        for (PihaoModel pihaoModel:danhaoModel.getPihaoModels()){
                            if (pihaoModel.isChk()){
                                pihaoModels.add(pihaoModel);
                            }
                        }
                    }
                    jsonStr = JsonHelper.toJson(pihaoModels,1);
                }else {
                    jsonStr = "";
                    mAdapter.getContents().put("订单号","");
                    mAdapter.notifyDataSetChanged();
                    AbToastUtil.showToast(this,"未选择订单，请重新选择！");
                }

                break;
            case GETPLATENUM:
                mAdapter.getContents().put("车牌号",value);
                mAdapter.notifyDataSetChanged();
                break;
        }

    }

    @Override
    public void getImgClick(int position) {
        switch (mData.get(position)){
            case "车牌号":
                if (TextUtils.equals(isCommit,"0")) {
                    Intent i = new Intent(ConfirmActivity.this, PlateNumberSelect.class);
                    startActivityForResult(i, GETPLATENUM);
                }
                break;
            case "订单号":
                if (TextUtils.equals(isCommit,"0")){
                    if(TextUtils.isEmpty(mAdapter.getContents().get("车牌号"))){
                        AbToastUtil.showToast(this,"车牌号为空，请核实！");
                    }
                    Intent intent=new Intent(this,ContractSelect.class);
                    intent.putExtra("dispatchId",mAdapter.getContents().get("单号"));
                    intent.putExtra("plateNum",mAdapter.getContents().get("车牌号"));
                    intent.putExtra("saverFactory",mAdapter.getContents().get("工厂代码"));
                    intent.putExtra("flag",flag);
                    intent.putExtra("mType",mType);
                    startActivityForResult(intent, GETPLAN);
                }
                break;
        }
    }
    @Override
    public void onBackPressed() {
        finish();
    }
}
